#include "DataGen.h"

#include "XlsxReader.h"

#include <regex>
#include <unordered_map>
#include <xxhash.h>

std::unordered_map<std::string, std::string> DataGen::dataMap;

std::vector<Data> DataGen::dataArray;

DataGen::DataGen() {

    XlsxReader xl;
    xl.OpenFile("productRetransmitItem_1716515175902.xlsx");
    xl.Parse();
    xl.CloseFile();
    zlog_i("解析完成");
    zlog_i("数据点数量: %ld", xl.dataList.size());
    dataArray.clear();
}

DataGen::~DataGen() {}

void DataGen::Init() {
    for (auto &item : XlsxReader::dataList) {
        dataMap[item.varName] = "0";
    }

    std::regex status("Status", std::regex::icase);
    std::regex fault("fault", std::regex::icase);
    std::regex alarm("alarm", std::regex::icase);

    for (auto data : XlsxReader::dataList) {
        if (std::regex_search(data.varName, status)) {
            statusDataArray.push_back(data);
        }
        else if (std::regex_search(data.varName, fault)) {
            faultDataArray.push_back(data);
        }
        else if (std::regex_search(data.varName, alarm)) {
            alarmDataArray.push_back(data);
        }
        else {
            measDataArray.push_back(data);
        }
    }

    // 将4个Array合并到一个Array中
    dataArray.insert(
        dataArray.end(), statusDataArray.begin(), statusDataArray.end());
    dataArray.insert(
        dataArray.end(), faultDataArray.begin(), faultDataArray.end());
    dataArray.insert(
        dataArray.end(), alarmDataArray.begin(), alarmDataArray.end());
    dataArray.insert(
        dataArray.end(), measDataArray.begin(), measDataArray.end());

    zlog_i("初始化完成");
    zlog_i("dataArray size: %ld", dataArray.size());
    zlog_i("生成数据");

    for (auto &data : dataArray) {
        std::string varName = data.devName + "/" + data.varName;
        dataMap[varName]    = "";
    }

    XXH64_hash_t hash;
    for (auto &data : dataArray) {
        std::string varName = data.devName + "/" + data.varName;
        hash                = XXH64(varName.c_str(), varName.size(), 0);
    }
}

void DataGen::Update() {
    for (auto &data : dataArray) {
        std::string varName = data.devName + "/" + data.varName;
        switch (data.type) {
            case DataType::BOOL:
                dataMap[varName] = std::to_string(GenRandomNum() % 2);
                break;
            case DataType::INT:
                dataMap[varName] = std::to_string(GenRandomNum());
                break;
            case DataType::FLOAT:
                dataMap[varName] = std::to_string(GenRandomNum() / 100.0);
                break;
            default:
                zlog_e("未知数据类型: %d", data.type);
                break;
        }
    }
}

int DataGen::GenRandomNum() { return rand() % 10000; }
